const { PrismaClient } = require("@prisma/client");
const bcrypt = require("bcrypt");

const prisma = new PrismaClient();

async function main() {
  console.log("开始初始化数据库...");

  try {
    // 1. 创建管理员用户
    const hashedPassword = await bcrypt.hash("123456", 10);

    const adminUser = await prisma.user.upsert({
      where: { username: "admin" },
      update: {},
      create: {
        username: "admin",
        password: hashedPassword,
        email: "admin@aiproducthome.com",
        role: "admin",
        status: true,
        display: true,
      },
    });

    console.log("✅ 管理员用户创建成功:", adminUser.username);

    // 2. 创建文章分类
    const articleCategories = await Promise.all([
      prisma.articleCategory.upsert({
        where: { name: "实用工具" },
        update: {},
        create: {
          name: "实用工具",
          description: "实用的AI工具和软件推荐",
          sort: 1,
          status: true,
        },
      }),
      prisma.articleCategory.upsert({
        where: { name: "产品趋势" },
        update: {},
        create: {
          name: "产品趋势",
          description: "AI产品发展趋势和前沿动态",
          sort: 2,
          status: true,
        },
      }),
      prisma.articleCategory.upsert({
        where: { name: "技术分析" },
        update: {},
        create: {
          name: "技术分析",
          description: "AI技术深度分析和洞察",
          sort: 3,
          status: true,
        },
      }),
      prisma.articleCategory.upsert({
        where: { name: "行业动态" },
        update: {},
        create: {
          name: "行业动态",
          description: "AI行业最新动态和资讯",
          sort: 4,
          status: true,
        },
      }),
      prisma.articleCategory.upsert({
        where: { name: "教程指南" },
        update: {},
        create: {
          name: "教程指南",
          description: "AI使用教程和操作指南",
          sort: 5,
          status: true,
        },
      }),
    ]);

    console.log(
      "✅ 文章分类创建成功:",
      articleCategories.map(c => c.name)
    );

    // 3. 创建案例分类
    const caseCategories = await Promise.all([
      prisma.caseCategory.upsert({
        where: { name: "AI教育" },
        update: {},
        create: {
          name: "AI教育",
          description: "AI在教育领域的应用案例",
          sort: 1,
          status: true,
        },
      }),
      prisma.caseCategory.upsert({
        where: { name: "AI编程" },
        update: {},
        create: {
          name: "AI编程",
          description: "AI在编程开发中的应用案例",
          sort: 2,
          status: true,
        },
      }),
      prisma.caseCategory.upsert({
        where: { name: "AI设计" },
        update: {},
        create: {
          name: "AI设计",
          description: "AI在设计创作中的应用案例",
          sort: 3,
          status: true,
        },
      }),
      prisma.caseCategory.upsert({
        where: { name: "AI营销" },
        update: {},
        create: {
          name: "AI营销",
          description: "AI在营销推广中的应用案例",
          sort: 4,
          status: true,
        },
      }),
    ]);

    console.log(
      "✅ 案例分类创建成功:",
      caseCategories.map(c => c.name)
    );

    // 4. 创建产品分类
    const productCategories = await Promise.all([
      prisma.productCategory.upsert({
        where: { name: "工作效率" },
        update: {},
        create: {
          name: "工作效率",
          description: "提升工作效率的AI产品",
          sort: 1,
          status: true,
        },
      }),
      prisma.productCategory.upsert({
        where: { name: "AI编程" },
        update: {},
        create: {
          name: "AI编程",
          description: "AI辅助编程开发工具",
          sort: 2,
          status: true,
        },
      }),
      prisma.productCategory.upsert({
        where: { name: "AI设计" },
        update: {},
        create: {
          name: "AI设计",
          description: "AI设计创作工具",
          sort: 3,
          status: true,
        },
      }),
      prisma.productCategory.upsert({
        where: { name: "AI写作" },
        update: {},
        create: {
          name: "AI写作",
          description: "AI写作辅助工具",
          sort: 4,
          status: true,
        },
      }),
      prisma.productCategory.upsert({
        where: { name: "AI图像" },
        update: {},
        create: {
          name: "AI图像",
          description: "AI图像生成和处理工具",
          sort: 5,
          status: true,
        },
      }),
    ]);

    console.log(
      "✅ 产品分类创建成功:",
      productCategories.map(c => c.name)
    );

    // 5. 创建示例文章
    const articles = await Promise.all([
      prisma.article.upsert({
        where: { id: 1 },
        update: {},
        create: {
          title: "深度学习的未来：机遇与挑战",
          slug: "deep-learning-future-opportunities-challenges",
          content: `
            <h2>引言</h2>
            <p>从 GPT-4 到 Sora，我们正处于一个技术爆炸的时代。人工智能的发展速度远超想象，为各个行业带来了前所未有的机遇。</p>
            
            <h2>核心挑战</h2>
            <p>第一个核心挑战是 <strong>可解释性 (Interpretability)</strong>。目前的深度学习模型大多像一个"黑箱"，我们知道输入和输出，却很难理解其内部的决策逻辑。</p>
            
            <p>第二个挑战是 <strong>数据依赖</strong>。高质量的标注数据是训练优秀模型的基石，但获取这些数据的成本极高。</p>
            
            <h2>未来展望</h2>
            <p>随着技术的不断进步，我们相信这些问题终将得到解决。AI将为人类带来更美好的未来。</p>
          `,
          summary: "从 GPT-4 到 Sora，我们正处于一个技术爆炸的时代，但前路并非一帆风顺...",
          author: "admin",
          categoryId: articleCategories[1].id,
          status: true,
          tags: ["深度学习", "AI技术", "行业趋势"],
          views: 2100,
          likes: 113,
          comments: 13,
          isTop: true,
          isRecommend: true,
          publishedAt: new Date("2025-01-09"),
          userId: adminUser.id,
          username: adminUser.username,
        },
      }),
      prisma.article.upsert({
        where: { id: 2 },
        update: {},
        create: {
          title: "普通人如何利用 AI 提升工作效率？",
          slug: "how-ordinary-people-use-ai-improve-work-efficiency",
          content: `
            <h2>前言</h2>
            <p>本文介绍5个实用 AI 工具，无需编程背景，普通人也能轻松上手。</p>
            
            <h2>推荐工具</h2>
            <h3>1. ChatGPT</h3>
            <p>最受欢迎的AI对话工具，可以帮助写作、翻译、编程等。</p>
            
            <h3>2. Notion AI</h3>
            <p>集成在Notion中的AI助手，提升笔记和文档创作效率。</p>
            
            <h3>3. Midjourney</h3>
            <p>强大的AI绘画工具，将文字描述转化为精美图像。</p>
            
            <h2>使用建议</h2>
            <p>建议从简单的任务开始，逐步探索AI的更多可能性。</p>
          `,
          summary: "本文介绍5个实用 AI 工具，无需编程背景...",
          author: "admin",
          categoryId: articleCategories[0].id,
          status: true,
          tags: ["AI工具", "工作效率", "实用指南"],
          views: 5800,
          likes: 204,
          comments: 45,
          isRecommend: true,
          publishedAt: new Date("2025-01-08"),
          userId: adminUser.id,
          username: adminUser.username,
        },
      }),
    ]);

    console.log(
      "✅ 示例文章创建成功:",
      articles.map(a => a.title)
    );

    // 6. 创建示例案例
    const cases = await Promise.all([
      prisma.case.upsert({
        where: { id: 1 },
        update: {},
        create: {
          title: "AI辅助编程：提升开发效率的实践案例",
          slug: "ai-assisted-programming-case-study",
          content: `
            <h2>项目背景</h2>
            <p>在软件开发过程中，重复性的代码编写和调试工作占据了大量时间。通过引入AI编程助手，我们显著提升了开发效率。</p>
            
            <h2>实施方案</h2>
            <p>使用GitHub Copilot和Cursor等AI编程工具，配合团队培训，让开发者掌握AI辅助编程的最佳实践。</p>
            
            <h2>效果评估</h2>
            <p>开发效率提升40%，代码质量保持稳定，团队满意度显著提高。</p>
          `,
          summary: "通过AI编程助手提升开发效率的实践案例",
          author: "admin",
          categoryId: caseCategories[1].id,
          status: true,
          tags: ["AI编程", "开发效率", "实践案例"],
          views: 1200,
          likes: 85,
          comments: 12,
          isTop: false,
          isRecommend: true,
          publishedAt: new Date("2025-01-07"),
          userId: adminUser.id,
          username: adminUser.username,
        },
      }),
    ]);

    console.log(
      "✅ 示例案例创建成功:",
      cases.map(c => c.title)
    );

    // 7. 创建示例产品
    const products = await Promise.all([
      prisma.product.upsert({
        where: { id: 1 },
        update: {},
        create: {
          title: "ChatGPT - 智能对话助手",
          slug: "chatgpt-intelligent-conversation-assistant",
          content: `
            <h2>产品介绍</h2>
            <p>ChatGPT是由OpenAI开发的强大AI对话模型，能够进行自然语言对话，协助用户完成各种任务。</p>
            
            <h2>主要功能</h2>
            <ul>
              <li>自然语言对话</li>
              <li>文本生成和编辑</li>
              <li>代码编写和调试</li>
              <li>翻译和语言学习</li>
            </ul>
            
            <h2>适用场景</h2>
            <p>适用于内容创作、编程辅助、学习辅导、商务沟通等多种场景。</p>
          `,
          summary: "OpenAI开发的强大AI对话模型，支持多种任务场景",
          author: "admin",
          categoryId: productCategories[0].id,
          status: true,
          screenshots: [],
          views: 5000,
          likes: 300,
          comments: 50,
          isTop: true,
          isRecommend: true,
          publishedAt: new Date("2025-01-06"),
          websiteUrl: "https://chat.openai.com",
          developerAvatar: "",
          developerNickname: "OpenAI",
          developerBio: "致力于确保人工智能造福全人类",
          userId: adminUser.id,
          username: adminUser.username,
        },
      }),
    ]);

    console.log(
      "✅ 示例产品创建成功:",
      products.map(p => p.title)
    );

    console.log("🎉 数据库初始化完成！");
    console.log("📝 默认管理员账户: admin / 123456");
    console.log("📊 创建了以下数据:");
    console.log(`   - 用户: 1个 (${adminUser.username})`);
    console.log(`   - 文章分类: ${articleCategories.length}个`);
    console.log(`   - 案例分类: ${caseCategories.length}个`);
    console.log(`   - 产品分类: ${productCategories.length}个`);
    console.log(`   - 示例文章: ${articles.length}篇`);
    console.log(`   - 示例案例: ${cases.length}个`);
    console.log(`   - 示例产品: ${products.length}个`);
  } catch (error) {
    console.error("❌ 数据库初始化失败:", error);
    throw error;
  }
}

main()
  .catch(e => {
    console.error("❌ 初始化失败:", e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });